// package-market/pages/lottery-edit-probability/index.js
const app = getApp();
import { NUMERAL_ZH } from '../../../constants/common';
import { navBack, tipToast } from '../../../common/env';
import { formatInputDecimal, deepClone } from '../../../common/utils';
import { ACTIVITY_STATUS_VALUE } from '../../../constants/activity';
import { LOTTERY_WIN_RATE } from '../../constants/lottery';

Page({
    data: {
        NUMERAL_ZH,
        LOTTERY_WIN_RATE,
        modifyFlag: true,
        activityInfo: {},
        lottery1: {},
    },
    onLoad(options) {
        app.event.addListener('sendLotteryActivityInfo', this._handleSendActivity.bind(this));
    },
    onUnload() {
        app.event.removeListener('sendLotteryActivityInfo');
    },
    _handleSendActivity(activityInfo) {
        const { lottery1 } = deepClone(activityInfo);
        lottery1.prizeRates.splice(activityInfo.activityProductWithSkus.length, 1);
        lottery1.prizeRates = lottery1.prizeRates.map(i => i / 10);
        const modifyFlag = !activityInfo.processStatus || activityInfo.processStatus === ACTIVITY_STATUS_VALUE.draft;
        this.setData({
            modifyFlag,
            activityInfo,
            lottery1,
        });
    },
    handleChange(e) {
        const rate = e.detail;
        const { index } = e.currentTarget.dataset;
        const { lottery1 } = this.data;
        lottery1.prizeRates[index] = formatInputDecimal(rate, 1);
        this.setData({
            lottery1,
        });
    },
    handleSave(e) {
        if (!this.data.modifyFlag) {
            navBack();
            return;
        }
        const { activityInfo, lottery1 } = this.data;
        const rateTotal = lottery1.prizeRates.reduce((s, c) => s + parseFloat(c <= 0 ? 0 : c), 0);
        if (!lottery1.prizeRates.every(i => i > 0)) {
            tipToast('请设置完整的中奖概率');
            return;
        } else if (rateTotal > 100) {
            tipToast('中奖概率之和不能超过100%');
            return;
        }
        lottery1.prizeRates = lottery1.prizeRates.map(i => i * 10);
        activityInfo.lottery1 = lottery1;
        app.event.trigger('getLotteryActivityInfo', activityInfo);
        navBack();
    },
})
